<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      Array.prototype.myReduce = function (cb, initVal) {
        if (this == null) {
          throw new TypeError("this is null or not defined");
        }
        if (typeof cb != "function") {
          throw new TypeError("is not a function ");
        }
        const arr = this;
        const len = arr.length;
        let k = 0;
        let acc;
        if (initVal !== undefined) {
          acc = initVal;
        } else {
          // 没传入初始值的时候，取数组中第一个非 empty 的值为初始值
          while (k < len && !(k in arr)) {
            k++;
          }
          if (k >= len) {
            throw new TypeError("Reduce of empty array with no initial value ");
          }
          acc = arr[k++];
        }

        while (k < len) {
          acc = cb(acc, arr[k], k, arr);
          k++;
        }
        return acc;
      };
    </script>
  </body>
</html>
